package com.aidex.biz.service.impl;

import com.aidex.biz.domain.AccountInfo;
import com.aidex.biz.domain.AccountLog;
import com.aidex.biz.domain.UserTixian;
import com.aidex.biz.mapper.UserTixianMapper;
import com.aidex.biz.service.*;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sms.ChuangLanSmsClient;
import com.aidex.system.service.CompanyService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 用户提现Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-10-27
 */
@Service
@Transactional(readOnly = true)
public class UserTixianServiceImpl extends BaseServiceImpl<UserTixianMapper, UserTixian> implements UserTixianService {
    private static final Logger log = LoggerFactory.getLogger(UserTixianServiceImpl.class);
    @Autowired
    private CompanyService companyService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private SmSSendService smSSendService;
    @Autowired
    private AccountInfoService accountInfoService;
    @Autowired
    private AccountLogService accountLogService;

    /**
     * 获取单条数据
     *
     * @param userTixian 用户提现
     * @return 用户提现
     */
    @Override
    public UserTixian get(UserTixian userTixian) {
        UserTixian dto = super.get(userTixian);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 用户提现id
     * @return 用户提现
     */
    @Override
    public UserTixian get(String id) {
        UserTixian dto = super.get(id);
        return dto;
    }


    /**
     * 查询用户提现列表
     *
     * @param userTixian 用户提现
     * @return 用户提现
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<UserTixian> findList(UserTixian userTixian) {
        return super.findList(userTixian);
    }

    /**
     * 分页查询用户提现列表
     *
     * @param userTixian 用户提现
     * @return 用户提现
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<UserTixian> findPage(UserTixian userTixian) {
        return super.findPage(userTixian);
    }

    /**
     * 保存用户提现
     *
     * @param userTixian
     * @return 结果
     */
    @Override
    public boolean save(UserTixian userTixian) {
        return super.save(userTixian);
    }


    /**
     * 删除用户提现信息
     *
     * @param userTixian
     * @return 结果
     */
    @Override
    public boolean remove(UserTixian userTixian) {
        return super.remove(userTixian);
    }

    /**
     * 批量删除用户提现
     *
     * @param ids 需要删除的用户提现ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteUserTixianByIds(String[] ids) {
        return mapper.deleteUserTixianByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param userTixian 用户提现
     * @return 结果
     */
    @Override
    public int findMaxSort(UserTixian userTixian) {
        return NumberUtils.nextOrder(mapper.findMaxSort(userTixian));
    }

    @Override
    public UserTixian findByOne() {
        return mapper.findByOne();
    }

    @Override
    @Transactional(readOnly = false)
    public JSONObject getTransferBatchesDetails(UserTixian userTixian) {
        Company company = companyService.get(AiDexConfig.getCompanyId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_batch_no", userTixian.getWxPayNo().split("/")[0]);
        jsonObject.put("out_detail_no", userTixian.getId());
        // 微信发起转账
        String result = wxPayService.transferBatchesOutDetailNo(company.getWechatMchid().trim(),
                company.getCertNo().trim(), company.getWechatMchKey().trim(), company.getCertKey().trim(), jsonObject);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (null == resultJson.getString("error") || StringUtils.isEmpty(resultJson.getString("error"))) {
            if ("SUCCESS".equals(resultJson.getString("detail_status")) && userTixian.getId().equals(jsonObject.getString("out_detail_no"))) {
                userTixian.setPayTime(new Date());
                userTixian.setStatus("2");
                userTixian.setRemark("-付款成功！");
                if ("1".equals(company.getSmsIsopen())) {
//                    smSSendService.sendSMS(company.getSmsBaoName(), company.getSmsBaoKey(), userTixian.getPhone(),
//                            company.getSmsqm(), "尊敬的" + userTixian.getPhone() + "用户，您的商户提现成功，已到微信零钱，请到微信查看");
                    ChuangLanSmsClient.sendSms(userTixian.getPhone(),"尊敬的" + userTixian.getPhone() +
                            "用户，您的商户提现成功，已到微信零钱，请到微信查看");
                }
            } else if ("FAIL".equals(resultJson.getString("detail_status"))) {
                AccountInfo accountInfo = accountInfoService.get(userTixian.getAccountId());
                accountInfo.setAccount(accountInfo.getAccount().add(userTixian.getMoney()));
                accountInfoService.save(accountInfo);
                AccountLog accountLog = new AccountLog();
                accountLog.setId(StringUtils.Getnum());
                accountLog.setIsNewRecord();
                accountLog.setUserAccountId(accountInfo.getId());
                accountLog.setMoney(userTixian.getMoney());
                accountLog.setType("提现失败-退回");
                accountLog.setStartMoney(accountInfo.getAccount().subtract(accountLog.getMoney()));
                accountLog.setEndMoney(accountLog.getStartMoney().add(accountLog.getMoney()));
                accountLog.setTargetAccountId(accountInfo.getId());
                accountLog.setCompanyId(company.getId());
                accountLogService.save(accountLog);
                userTixian.setStatus("-1");
                userTixian.setRemark(resultJson.getString("fail_reason"));
                if ("1".equals(company.getSmsIsopen())) {
//                    smSSendService.sendSMS(company.getSmsBaoName(), company.getSmsBaoKey(), userTixian.getPhone(),
//                            company.getSmsqm(), "尊敬的" + userTixian.getPhone() + "用户，您提现失败，金额已退回账户余额");
                    ChuangLanSmsClient.sendSms(userTixian.getPhone(),
                            "尊敬的" + userTixian.getPhone() + "用户，您提现失败!请联系平台！");
                }
            }
        } else {
            JSONObject jsonObjectError = resultJson.getJSONObject("error");
            userTixian.setRemark(jsonObjectError.getString("message"));
            userTixian.setStatus("100");
        }
        resultJson.put("message", userTixian.getRemark() != null ? userTixian.getRemark() : "打款成功");
        super.save(userTixian);// 保存提现状态
        return resultJson;
    }

    @Override
    public UserTixian findByStatus() {
        return mapper.findByStatus();
    }

    @Override
    public List<UserTixian> findListCount(UserTixian userTixian) {
        return mapper.findListCount(userTixian);
    }

    /**
     * 查询用户所有提现信息
     *
     * @param userInfoId
     * @return
     */
    public Integer getUserTixianAllAmount(@Param("userInfoId") String userInfoId) {
        return mapper.getUserTixianAllAmount(userInfoId);
    }
}
